package org.cypress.rtpack.common.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.cypress.rtpack.controller.SoeController;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * Created by IntelliJ IDEA.
 * User: Getty
 * Date: 2019/12/3
 * Time: 16:11
 */
@Slf4j
@Aspect
@Component
public class WebControllerLogAop {
    private static final Logger log = LoggerFactory.getLogger(WebControllerLogAop.class);
    @Pointcut("execution(public * com.ksyun.standard.controller.*.*(..))")
    public void webLog(){

    }
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint){
        try {
            log.info("doBefore...");
            //方法前被调用;
            Signature signature = joinPoint.getSignature();
            //方法调用 signature.getName()
            //方法所在包 signature.getDeclaringTypeName()
            log.info(signature.getDeclaringType().toString());

            MethodSignature methodSignature = (MethodSignature) signature;
            String[] methodParams = methodSignature.getParameterNames();
            log.info("参数名:" + Arrays.toString(methodParams) + " 参数值: " + Arrays.toString(joinPoint.getArgs()));

            //请求url记录;
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            log.info("请求url: " + request.getRequestURL().toString());
            log.info("请求方法: " + request.getMethod());
            log.info("请求类:" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        }catch (Exception e){
            log.error("接口请求切面拦截异常", e);
        }

    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturn(Object ret) {
        //处理完请求,返回内容;
//        log.info("AfterReturning....");
//        log.info("方法返回值: " + ret);
    }

    @AfterThrowing("webLog()")
    public void throwss(JoinPoint jp){
        //后置异常通知;方法异常时执行
        log.info("AfterThrowing...");
    }

    @After("webLog()")
    public void after(){
//        log.info("after.....");
    }

    /**
     * 环绕通知,环绕增强，相当于MethodInterceptor
     * @param pjp
     * @return
     */
    @Around("webLog()")
    public Object arround(ProceedingJoinPoint pjp) {
        try {
            Object o = pjp.proceed();
//            log.info("arround......");
            return o;
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
    }
}
